package com.yuncheng.spcyApi.flowService;

import cn.hutool.core.date.DateUtil;
import com.yuncheng.entity.YcSysOrg;
import com.yuncheng.entity.YcSysUser;
import com.yuncheng.vo.GetKsKz;
import com.yuncheng.vo.CurrentUserVo;
import org.apache.commons.collections.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yuncheng.spcyApi.busService.BusService;
import com.yuncheng.spcyApi.config.SpcyMinioUtils;
import com.yuncheng.spcyApi.constant.common.BusinessConstant;
import com.yuncheng.spcyApi.constant.common.ClientJumpUrlConstant;
import com.yuncheng.spcyApi.constant.common.LogConstant;
import com.yuncheng.spcyApi.constant.common.SpcyConstant;
import com.yuncheng.spcyApi.constant.flow.HfrwFlowConstant;
import com.yuncheng.spcyApi.constant.sys.SysConfigConstant;
import com.yuncheng.spcyApi.entity.*;
import com.yuncheng.exception.BusinessException;
import com.yuncheng.spcyApi.service.*;
import com.yuncheng.spcyApi.service.impl.YcSysUserServiceImpl;
import com.yuncheng.spcyApi.utils.*;
import com.yuncheng.spcyApi.vo.common.Result;
import com.yuncheng.spcyApi.vo.flow.AgentVo;
import com.yuncheng.spcyApi.vo.hfrw.HfrwFlowVo;
import com.yuncheng.spcyApi.vo.sqsx.SqsxZbrVo;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import utils.DateConversionUtils;
import utils.LogUtils;
import utils.ObjectToMapUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.*;

@Component(value = "hfrwFlowService")
public class HfrwFlowService extends FlowService {

    private static final Logger log = LoggerFactory.getLogger(HfrwFlowService.class);

    @Resource
    @Lazy
    private HfrwFlowConstant flowConstant;

    @Resource
    @Lazy
    private ISpcySqsxJobService spcySqsxJobService;

    @Resource
    @Lazy
    private ISysUserFgldService sysUserFgldService;

    @Resource
    @Lazy
    private ISpcySqsxBaiscService spcySqsxBaiscService;

    @Resource
    @Lazy
    private ISpcySqsxHfrwlcService spcySqsxHfrwlcService;

    @Resource
    @Lazy
    private YcSysUserServiceImpl ycSysUserService;

    @Resource
    @Lazy
    private IYcSysOrgService ycSysOrgService;

    @Resource
    @Lazy
    private BusService busService;

    @Resource
    @Lazy
    private ISpcyLogService spcyLogService;

    @Resource
    @Lazy
    private ISpcySqsxWjjlService spcySqsxWjjlService;

    @Resource
    @Lazy
    private ISpcyWjWjjbxxService spcyWjWjjbxxService;

    @Resource
    @Lazy
    private ISpcyWjWjtxjbxxService spcyWjWjtxjbxxService;

    @Resource
    private SpcyMinioUtils spcyMinioUtils;

    @Resource
    private LocalFileUploadUtils localFileUploadUtils;

    @Resource
    private SmsUtils smsUtils;

    public Result handleFlow(HfrwFlowVo flowVo, SpcySqsxJob nowJob, String jobId, String hfrwid, String submitType, String opinion){
        // 当前流程任务
        if (StringUtils.isNotBlank(jobId)) {
            nowJob = spcySqsxJobService.getById(jobId);
        }

        if (nowJob == null){
            return Result.error("当前流程任务不存在，请重试");
        }

        if (StringUtils.isBlank(hfrwid)){
            hfrwid = nowJob.getFpid();
        }

        // 提交按钮
        if (submitType.equals(HfrwFlowConstant.SUBMIT_TYPE_SUBMIT)) {
            if (nowJob == null) {
                return Result.error("当前流程任务不存在");
            }

            if (StringUtils.isBlank(nowJob.getFhjmc())){
                return Result.error("当前流程任务-环节名称不存在，请联系管理员！");
            }
        }
        CurrentUserVo currentUser = GetCurrentUserUtils.getCurrentUser();
        if (currentUser == null){
            return Result.error("登录已失效，请重新登录");
        }

        // 判断当前环节是否为主流程
        String currentNode = nowJob.getFhjmc();
        boolean isManFlow = this.verifyMainFlow(currentNode);

        // 主流程处理
        if (isManFlow){

            String nextNodeName = flowConstant.getNextNodeName(currentNode);
            flowVo.setNextNode(nextNodeName);

            if (currentNode.equals(HfrwFlowConstant.HJMC_HFJH)){

                // 流程环节处理
                Result httpResult = handleNodeName(flowVo, submitType, nowJob, hfrwid, opinion);
                if (!httpResult.isSuccess()) {
                    return httpResult;
                }

                if (submitType.equals(HfrwFlowConstant.SUBMIT_TYPE_SUBMIT)) {
                    SpcySqsxHfrwlc hfrw = spcySqsxHfrwlcService.getById(hfrwid);
                    if (hfrw != null && StringUtils.isNotBlank(hfrw.getFsqsxid())) {

                        if (StringUtils.isNotBlank(hfrw.getFsqsxid())) {
                            SpcySqsxBasic sqsx = spcySqsxBaiscService.getById(hfrw.getFsqsxid());
                            if (sqsx != null) {
                                sqsx.setFhfzt(HfrwFlowConstant.HFZT_YHF);
                                spcySqsxBaiscService.updateById(sqsx);
                            }
                        }
                    }
                }

            }
            else if (currentNode.equals(HfrwFlowConstant.HJMC_HFJHSS)){

                // 流程环节处理
                Result httpResult = handleNodeName(flowVo, submitType, nowJob, hfrwid, opinion);
                if (!httpResult.isSuccess()) {
                    return httpResult;
                }

            }
            else if (currentNode.equals(HfrwFlowConstant.HJMC_HFJGSP)){

                // 流程环节处理
                Result httpResult = handleNodeName(flowVo, submitType, nowJob, hfrwid, opinion);
                if (!httpResult.isSuccess()) {
                    return httpResult;
                }

                if (submitType.equals(HfrwFlowConstant.SUBMIT_TYPE_SUBMIT)){
                    SpcySqsxHfrwlc hfrw = spcySqsxHfrwlcService.getById(hfrwid);
                    // 初始化-反馈意见处置-子流程
                    if (hfrw != null && StringUtils.isNotBlank(hfrw.getFfkyjczks())) {
                        Result subResult = this.initSubJob(hfrwid, currentUser);
                        if (!subResult.isSuccess()) {
                            return subResult;
                        }
                    }
                }

            }
            else if (currentNode.equals(HfrwFlowConstant.HJMC_FKYJCZ)){

                // 流程环节处理
                Result httpResult = handleNodeName(flowVo, submitType, nowJob, hfrwid, opinion);
                if (!httpResult.isSuccess()) {
                    return httpResult;
                }

            }
            else if (currentNode.equals(HfrwFlowConstant.HJMC_GDBJ)){

                // 流程环节处理
                Result httpResult = handleNodeName(flowVo, submitType, nowJob, hfrwid, opinion);
                if (!httpResult.isSuccess()) {
                    return httpResult;
                }

                if (submitType.equals(HfrwFlowConstant.SUBMIT_TYPE_SUBMIT)){
                    SpcySqsxHfrwlc hfrw = spcySqsxHfrwlcService.getById(hfrwid);
                    if (hfrw != null){
                        String sqsxid = hfrw.getFsqsxid();
                        hfrw.setFlczt(HfrwFlowConstant.HJMC_LCJS);
                        hfrw.setFgdrq(new Date());
                        spcySqsxHfrwlcService.updateById(hfrw);

                        if (StringUtils.isNotBlank(sqsxid)){
                            SpcySqsxBasic sqsx = spcySqsxBaiscService.getById(sqsxid);
                            if (sqsx != null){
                                sqsx.setFhfzt(HfrwFlowConstant.HFZT_YHF);
                                spcySqsxBaiscService.updateById(sqsx);
                            }
                        }
                    }
                }

            }
            else {

                // 流程环节处理
                Result httpResult = handleNodeName(flowVo, submitType, nowJob, hfrwid, opinion);
                if (!httpResult.isSuccess()) {
                    return httpResult;
                }

            }

        }

        // 子流程处理
        if (!isManFlow){

            // 子流程
            String subNextNodeName = HfrwFlowConstant.getSubNextNodeName(currentNode);
            flowVo.setNextNode(subNextNodeName);

            if (currentNode.equals(HfrwFlowConstant.SUB_HJMC_KSQS)){

                if (submitType.equals(HfrwFlowConstant.SUBMIT_TYPE_SUBMIT)){
                    // getUserNameByUserId 保持-填处置措施人
                    if (StringUtils.isNotBlank(flowVo.getDbrid())) {
                        String dbrid = flowVo.getDbrid();
                        String dbr = this.getUserNameByUserId(dbrid);
                        this.updateCzcsBlrJbxx(dbrid, dbr, hfrwid, true, false);
                    }
                }

                // 流程环节处理
                Result httpResult = handleNodeName(flowVo, submitType, nowJob, hfrwid, opinion);
                if (!httpResult.isSuccess()) {
                    return httpResult;
                }

            }
            else if (currentNode.equals(HfrwFlowConstant.SUB_HJMC_TCZCS)){

                // 流程环节处理
                Result httpResult = handleNodeName(flowVo, submitType, nowJob, hfrwid, opinion);
                if (!httpResult.isSuccess()) {
                    return httpResult;
                }

            }
            else if (currentNode.equals(HfrwFlowConstant.SUB_HJMC_FGLDSH)){

                // 流程环节处理
                Result httpResult = handleNodeName(flowVo, submitType, nowJob, hfrwid, opinion);
                if (!httpResult.isSuccess()) {
                    return httpResult;
                }

                if (submitType.equals(HfrwFlowConstant.SUBMIT_TYPE_SUBMIT)){
                    // 主流程 - 反馈意见处置 - 提交
                    // 反馈意见处置 待办
                    List<SpcySqsxJob> fkyjJobList = spcySqsxJobService.list(new LambdaQueryWrapper<SpcySqsxJob>()
                            .eq(SpcySqsxJob::getFpid, hfrwid)
                            .eq(SpcySqsxJob::getFhjmc, HfrwFlowConstant.HJMC_FKYJCZ)
                            .eq(SpcySqsxJob::getFlcmc, flowConstant.getFlowName())
                            .ne(SpcySqsxJob::getFblzt, SpcyConstant.BLZT_YB));
                    if (org.apache.commons.collections.CollectionUtils.isNotEmpty(fkyjJobList)) {

                        String nextNodeName = flowConstant.getNextNodeName(HfrwFlowConstant.HJMC_FKYJCZ);
                        HfrwFlowVo hfrwFlowVo = new HfrwFlowVo();
                        hfrwFlowVo.setNextNode(nextNodeName);
                        hfrwFlowVo.setJobid(fkyjJobList.get(0).getId());
                        hfrwFlowVo.setHfrwid(hfrwid);
                        hfrwFlowVo.setSmgflag(flowVo.getSmgflag());
                        hfrwFlowVo.setMap(new HashMap<>());

                        //办理掉当前环节
                        SpcySqsxJob job = fkyjJobList.get(0);
                        Result result = this.passJob(job, hfrwid, nextNodeName, "", currentUser, opinion, false);
                        if (!result.isSuccess()){
                            return result;
                        }

                        /*Result subResult = handleNodeName(hfrwFlowVo, submitType, fkyjJobList.get(0), hfrwid, opinion);
                        if (!subResult.isSuccess()) {
                            return subResult;
                        }*/
                    }
                }

            }
            else {

                // 流程环节处理
                Result httpResult = handleNodeName(flowVo, submitType, nowJob, hfrwid, opinion);
                if (!httpResult.isSuccess()) {
                    return httpResult;
                }

            }
        }

        return Result.ok("操作成功");
    }

    public Result handleNodeName(HfrwFlowVo flowVo,String submitType, SpcySqsxJob job, String sqsxId, String opinion){
        HashMap<String, Object> map = flowVo.getMap();
        String dbrid = flowVo.getDbrid();// 下环节待办人
        String smgflag = flowVo.getSmgflag(); // 短信发送标志
        String smsContent = flowVo.getSmsContent(); // 短信内容
        boolean isSubmit = true; // 是否提交流程
        Result res = null;

        // 保存按钮
        if (submitType.equals(HfrwFlowConstant.SUBMIT_TYPE_SAVE)){
            if (map != null) {
                res = this.updateJbxx(map, sqsxId, job);
                if (!res.isSuccess()) {
                    return res;
                } else {
                    return Result.ok("保存成功");
                }
            }
        }

        // 提交按钮
        if (submitType.equals(HfrwFlowConstant.SUBMIT_TYPE_SUBMIT)){
            if (map != null) {
                res = this.updateJbxx(map, sqsxId, job);
                if (!res.isSuccess()) {
                    return res;
                }
            }

            // 流程任务id
            String jobId = "";
            if (job != null){
                jobId = job.getId();
            }

            // 提交流程任务,待办人是否为空，指定待办人
            if (isSubmit) {
                String nextNode = flowVo.getNextNode();
                if (StringUtils.isBlank(dbrid)) {
                    // 提交-流程任务
                    res = this.passJob(sqsxId, jobId, opinion, nextNode, "");
                } else {
                    // 提交-流程任务
                    res = this.passJob(sqsxId, jobId, opinion, nextNode, dbrid);
                }
            }
            if (!res.isSuccess()){
                return res;
            }else {
                SpcySqsxJob nowJob = (SpcySqsxJob)res.getResult();
                // 接收返回的流程任务，如果返回的流程任务id不相等，发送短信
                if (nowJob != null && !jobId.equals(nowJob.getId()) && StringUtils.isNotBlank(smgflag) && smgflag.equals("是")){
                    if (StringUtils.isNotBlank(smsContent)) {
                        busService.sendSmsToPassJob(nowJob);
                    }else {
                        busService.sendNextNodeSmsContent(nowJob,smsContent);
                    }
                }
            }
        }

        return Result.ok("提交成功");
    }

    /**
     * 从以移送的申请事项中，选择回访任务
     * @param sqsxid 申请事项id
     */
    public Result selectHfrwBySqsx(String sqsxid){
        Map resultMap = new HashMap();

        CurrentUserVo currentUser = GetCurrentUserUtils.getCurrentUser();
        if (currentUser == null){
            return Result.error("当前登录已失效，请重新登录！");
        }

        if (StringUtils.isBlank(sqsxid)){
            return Result.error("申请事项参数为空，请联系管理员！");
        }
        SpcySqsxBasic sqsx = spcySqsxBaiscService.getById(sqsxid);
        if (sqsx == null){
            return Result.error("当前申请事项不存在，请联系管理员！");
        }

        // 判断当前申请事项是否已经-回访了
        List<SpcySqsxHfrwlc> hfrwList = spcySqsxHfrwlcService.list(new LambdaQueryWrapper<SpcySqsxHfrwlc>()
                .eq(SpcySqsxHfrwlc::getFsqsxid, sqsxid));
        if (CollectionUtils.isNotEmpty(hfrwList)){
            String msg = "当前申请事项已经回访过了，流程处于【"+hfrwList.get(0).getFlczt()+"】";
            log.error(msg);
            return Result.error(msg);
        }

        // 生成回访任务
        SpcySqsxHfrwlc hfrwlc = new SpcySqsxHfrwlc();
        String hfrwid = GetUuIdUtils.ReplaceUuId();
        hfrwlc.setId(hfrwid);
        hfrwlc.setFsqsxid(sqsxid);
        hfrwlc.setFhfdd(sqsx.getFqymc());
//        hfrwlc.setFfkyjczks(this.getDeptName(sqsx.getFywflcode()));
        hfrwlc.setFhfkssj(DateConversionUtils.DateToDays(new Date()));
        hfrwlc.setFlczt(HfrwFlowConstant.LCZT_BLZ);
        hfrwlc.setFgxjcfj(sqsx.getFcygcybm());

        boolean save = spcySqsxHfrwlcService.save(hfrwlc);
        if (save){

            if (sqsx != null){
                sqsx.setFhfzt(HfrwFlowConstant.HFZT_HFZ);
                spcySqsxBaiscService.updateById(sqsx);
            }

            // 初始化
            Result result = this.initJob(hfrwid, currentUser);
            if (!result.isSuccess()){
                return Result.error(result.getMessage());
            }

            // 获取流程详情
            SpcySqsxJob job = (SpcySqsxJob) result.getResult();
            resultMap = this.getJobConcernByJobId(job.getId(),hfrwid);
        }

        return Result.ok(resultMap);
    }

    /**
     * 发给每个企业一个函
     */
    public Result sendQyLetter(java.lang.String hfrwid){
        // 文件
        List<SpcySqsxWjjl> wjjlList = this.queryFileList(hfrwid);

        SpcySqsxHfrwlc hfrw = spcySqsxHfrwlcService.getById(hfrwid);
        if (hfrw == null){
            return Result.error("当前回访任务数据不存在，请刷新重试并联系管理员！");
        }

        java.lang.String sqsxid = hfrw.getFsqsxid();

        SpcySqsxBasic sqsx = spcySqsxBaiscService.getById(sqsxid);
        if (sqsx != null){
            if (CollectionUtils.isEmpty(wjjlList)){
                return Result.error("没有发送的相关文件！");
            }

            // 给企业发送函
            Result result = busService.sendEmailToQyInHfrw(sqsxid, sqsx, wjjlList.get(0),true);
            if (!result.isSuccess()){
                return result;
            }
        }

        return Result.ok();
    }

    /**
     * 发送短信
     */
    public Result sendSmsToQy(String hfrwid) throws NoSuchAlgorithmException, IOException, InvalidKeySpecException {
        SpcySqsxHfrwlc hfrw = spcySqsxHfrwlcService.getById(hfrwid);
        if (hfrw == null){
            return Result.error("当前回访任务数据不存在，请刷新重试并联系管理员！");
        }
        if (StringUtils.isNotBlank(hfrw.getFhfwjid())){
            return Result.error("当前已经发送过问卷了！");
        }

        StringBuffer msg = new StringBuffer();
        String phone = "";

        String fsqsxid = hfrw.getFsqsxid();
        SpcySqsxBasic sqsx = spcySqsxBaiscService.getById(fsqsxid);
        if (sqsx != null){
            String fqylxrdh = sqsx.getFqylxrdh();
            if (StringUtils.isBlank(fqylxrdh)){
                return Result.error("企业联系人电话不存在！");
            }

            /**
             * 初始化问卷
             */
            SpcyWjWjtxjbxx wjtxjbxx = new SpcyWjWjtxjbxx();
            wjtxjbxx.setId(ClientJumpUrlConstant.WJ_ID);
            wjtxjbxx.setFsfdwmc(sqsx.getFqymc());
            wjtxjbxx.setFsfdwdz(sqsx.getFxxdz());
            wjtxjbxx.setFlxr(sqsx.getFqylxr());
            wjtxjbxx.setFlxdh(sqsx.getFqylxrdh());

            String ysjId = wjtxjbxx.getId(); // 原问卷id
            String djId = GetUuIdUtils.ReplaceUuId(); // 新问卷id

            SpcyWjWjjbxx ySjjbxx = spcyWjWjjbxxService.getById(ysjId);
            if (ySjjbxx == null){
                return Result.error("问卷不存在，青刷新重试");
            }

            spcyWjWjtxjbxxService.initWjtxjbxx(djId,ysjId,ySjjbxx,wjtxjbxx); // 初始化问卷

            msg.append(sqsx.getFqymc()).append(": ");
            msg.append(BusinessConstant.Dw_NAME).append("现对已完成的事项，");
            if (StringUtils.isNotBlank(sqsx.getFsqdbh())){
                msg.append("校核码为[").append(sqsx.getFsqdbh()).append("]的申请事项[").append(sqsx.getFsxmc()).append("]");
            }else {
                msg.append("申请事项为[").append(sqsx.getFsxmc()).append("]");
            }
            msg.append("进行回访调查，现有一份问卷需要贵企业完成，问卷链接如下：");
            msg.append(ClientJumpUrlConstant.sendSmsHfrwByWj_Url).append(djId).append("\n");
            msg.append("发送日期：").append(DateConversionUtils.DateToYMDHMSChineseString(new Date()));

            phone = fqylxrdh;

            hfrw.setFhfwjid(djId);
        }

//        String flag = smsUtils.AFGLHLA(phone, msg.toString());
        String flag = "成功";
        // 发送短信成功
        if (flag.contains(SysConfigConstant.SMS_FLAG)){
            spcySqsxHfrwlcService.updateById(hfrw);
        }

        return Result.ok("发送成功");
    }

    /**
     * 撤回流程
     * @param jobid
     * @param opinion
     * @return
     */
    public Result returnFlow(String jobid,String opinion){
        if (StringUtils.isBlank(jobid)){
            return Result.error("参数丢失，请联系管理员");
        }
        SpcySqsxJob nowJob = spcySqsxJobService.getById(jobid);

        if (nowJob == null){
            return Result.error("当前流程任务不存在，请刷新重试");
        }

        if (StringUtils.isNotBlank(nowJob.getFblzt()) && nowJob.getFblzt().equals(SpcyConstant.BLZT_YB)){
            return Result.error("当前环节【"+nowJob.getFhjmc()+"】已经办理，无法撤回");
        }

        String nowNode = nowJob.getFhjmc(); // 当前环节
        String previousName = ""; // 上环节名称

        // 判断是否为主流程
        boolean isMainFlow = this.verifyMainFlow(nowNode);
        if (isMainFlow) {
            previousName = flowConstant.getPreviousName(nowNode);
        }else {
            previousName = flowConstant.getPreviousSubName(nowNode);
        }

        StringBuffer logNr = new StringBuffer("撤回流程：\n");

        // 判断是否为第一个环节
        if (nowNode.equals(previousName)){
            spcySqsxJobService.removeById(jobid);
            logNr.append("环节名称").append("[").append(nowNode).append("]。");

            // 修改回访状态-处于第一个环节
            if (nowNode.equals(HfrwFlowConstant.HJMC_HFJH) && StringUtils.isNotBlank(nowJob.getFpid())){
                SpcySqsxHfrwlc hfrw = spcySqsxHfrwlcService.getById(nowJob.getFpid());
                if (hfrw != null && StringUtils.isNotBlank(hfrw.getFsqsxid())){
                    spcySqsxHfrwlcService.removeById(nowJob.getFpid());

                    SpcySqsxBasic sqsx = spcySqsxBaiscService.getById(hfrw.getFsqsxid());
                    if (sqsx != null){
                        sqsx.setFhfzt(HfrwFlowConstant.HFZT_WHF);
                        spcySqsxBaiscService.getById(sqsx);
                    }
                }

            }

        } else {

            // 上环节
            String fsyhjid = nowJob.getFsyhjid();
            if (StringUtils.isNotBlank(fsyhjid)) {
                SpcySqsxJob preJob = spcySqsxJobService.getById(fsyhjid);
                if (preJob != null) {
                    preJob.setFblzt(SpcyConstant.BLZT_TH);
                    preJob.setFthyj(opinion);
                    spcySqsxJobService.updateById(preJob);
                }
            }

            spcySqsxJobService.removeById(jobid);
            logNr.append("环节名称").append("[").append(nowNode).append("]");
        }

        if (StringUtils.isNotBlank(opinion)){
            logNr.append("\n").append("撤回意见").append("[").append(opinion).append("]。");
        }

        spcyLogService.addLogs(flowConstant.getFlowName()+"-"+nowNode,logNr.toString(),nowJob.getFpid(),SpcyConstant.LOGS_SYS_TYPE_TH,SpcyConstant.LOGS_SYS_TYPE_TH);

        return Result.ok("撤回成功");
    }

    /**
     * 终止流程
     */
    public Result endFlowJob(String jobid){
        if (StringUtils.isBlank(jobid)){
            return Result.error("流程参数为空");
        }
        SpcySqsxJob job = spcySqsxJobService.getById(jobid);
        if (job == null){
            return Result.error("当前流程记录不存在，请刷新重试");
        }
        if (StringUtils.isNotBlank(job.getFblzt()) && job.getFblzt().equals(SpcyConstant.BLZT_YB)){
            return Result.error("当前流程记录已经结束");
        }
        job.setFblzt(SpcyConstant.BLZT_YB); // 已办
        boolean flag = spcySqsxJobService.updateById(job);
        if (flag) {
            String log = "终止流程-环节名称-[" + job.getFhjmc() + "]。";
            spcyLogService.addLogs(flowConstant.getFlowName()+"-"+job.getFhjmc(), log, job.getFpid(), SpcyConstant.LOGS_SYS_TYPE_TJ, SpcyConstant.LOGS_SYS_TYPE_TJ);
        }

        return Result.ok("终止成功");
    }

    /**
     * 上传文件
     */
    public Result uploadFile(MultipartFile[] uploadFile, String hfrwid){

        if (StringUtils.isEmpty(hfrwid)){
            return Result.error("回访任务参数不能为空");
        }

        if (uploadFile == null || uploadFile.length == 0) {
            return Result.error("上传失败,请先选择文件");
        }

        for (MultipartFile file : uploadFile) {

            String originalFilename = file.getOriginalFilename();
            // 文件类型
            String wjlx = originalFilename.substring(originalFilename.lastIndexOf("."));

            // 文件名
            String fileName = file.getOriginalFilename().substring(0, file.getOriginalFilename().lastIndexOf("."));

            SpcySqsxWjjl spcySqsxWjjl = new SpcySqsxWjjl();

            String sjmc = HfrwFlowConstant.FILE_TYPE+"-"+GetUuIdUtils.NotReplaceUuId();
            String wjccmc = sjmc + wjlx;
            String nowDay = DateUtil.today(); // 获取当前日期 yyyy-MM-dd
            String newDir = nowDay;
            String newDir2 = SpcyConstant.WJJL_FILE_BASE_URL + "/" + newDir; // 实际上传文件目录

            spcyMinioUtils.uploadFile(file,newDir2+"/"+wjccmc); // 上传文件

            String Id = GetUuIdUtils.NotReplaceUuId();
            spcySqsxWjjl.setId(Id);
            spcySqsxWjjl.setFpid(hfrwid);
            spcySqsxWjjl.setFwjxsmc(fileName);
            spcySqsxWjjl.setFwjlx(wjlx);
            spcySqsxWjjl.setFwjlx1(HfrwFlowConstant.FILE_TYPE);
            spcySqsxWjjl.setFwjlx2(HfrwFlowConstant.FILE_TYPE);
            spcySqsxWjjl.setFwjccmc(wjccmc);
            String cflj = "/" + newDir +"/" + wjccmc;
            spcySqsxWjjl.setFcflj(cflj);
            boolean flag = spcySqsxWjjlService.save(spcySqsxWjjl);
            if (flag) {
                String czContent = LogConstant.LOGS_SQSX_HFRWLC+"-上传文件: ";
                Map<String, Object> wjjlMap = ObjectToMapUtils.objectToMap(spcySqsxWjjl);
                czContent += LogUtils.MapToStringMethod(wjjlMap);
                spcyLogService.addLogs(LogConstant.LOGS_SQSX_HFRWLC, czContent, hfrwid, LogConstant.LOGS_SQSX_WJJL, SpcyConstant.LOGS_SYS_TYPE_BC);
            }

        }

        return Result.ok("操作成功");
    }

    /**
     * 下载文件
     * @param id 文件记录id
     */
    public void downloadFile(String id, HttpServletResponse response){
        if (StringUtils.isBlank(id)){
            throw new BusinessException("下载失败，文件记录参数为空！");
        }
        SpcySqsxWjjl wjjl = spcySqsxWjjlService.getById(id);
        if (wjjl == null){
            throw new BusinessException("下载失败，文件记录不存在，请刷新重试！");
        }
        if (StringUtils.isBlank(wjjl.getFcflj())){
            throw new BusinessException("下载失败，文件记录中的附件为空！");
        }

        spcyMinioUtils.download(localFileUploadUtils.getSqsxWjjlRelativeUrl(wjjl.getFcflj()), response); // 下载文件
    }

    /**
     * 删除文件
     * @param id 文件记录id
     */
    public Result deleteFile(String id){
        if (StringUtils.isBlank(id)){
            throw new BusinessException("删除文件失败，文件记录参数为空！");
        }
        SpcySqsxWjjl wjjl = spcySqsxWjjlService.getById(id);
        if (wjjl == null){
            throw new BusinessException("删除文件失败，文件记录不存在，请刷新重试！");
        }
        spcySqsxWjjlService.removeById(id);
        if (StringUtils.isNotBlank(wjjl.getFcflj())) {
            spcyMinioUtils.removeObject(localFileUploadUtils.getSqsxWjjlRelativeUrl(wjjl.getFcflj())); // 删除文件
        }


        return Result.ok("操作成功");
    }

    /**
     * 查询文件
     * @param hfrwid 回访任务id
     */
    public List<SpcySqsxWjjl> queryFileList(String hfrwid){
        if (StringUtils.isBlank(hfrwid)){
            throw new BusinessException("回访任务参数不能为空");
        }

        List<SpcySqsxWjjl> wjjlList = spcySqsxWjjlService.list(new LambdaQueryWrapper<SpcySqsxWjjl>()
                .eq(SpcySqsxWjjl::getFpid, hfrwid)
                .eq(SpcySqsxWjjl::getFwjlx1, HfrwFlowConstant.FILE_TYPE)
                .eq(SpcySqsxWjjl::getFwjlx2,HfrwFlowConstant.FILE_TYPE)
                .orderByDesc(SpcySqsxWjjl::getCreateTime));

        return wjjlList;
    }

    /**
     * 获取当前流程任务相关信息
     * @param jobid 流程任务id
     */
    public Map getJobConcernByJobId(String jobid,String hfrwid){
        Map map = new HashMap();

        SpcySqsxJob job = new SpcySqsxJob();

        // 当前流转记录
        if (StringUtils.isNotBlank(jobid)) {
            job = spcySqsxJobService.getById(jobid);
        }

        if (StringUtils.isBlank(hfrwid) && job != null) {
            hfrwid = job.getFpid();
        }

        // 基本信息
        SpcySqsxHfrwlc hfrw = spcySqsxHfrwlcService.getById(hfrwid);

        // 申请事项
        SpcySqsxBasic sqsx = spcySqsxBaiscService.getById(hfrw.getFsqsxid());

        // 流程任务流传记录
        List<SpcySqsxJob> jobList = this.getJobListByHfrwid(hfrwid);

        // 获取下环节待办人
        List<AgentVo> dbrListByMap = new ArrayList<>();
        String nextNode = ""; // 下环节名称

        if (job != null) {
            String currentNode = job.getFhjmc();
            boolean isMainFlow = this.verifyMainFlow(currentNode); // 判断是否为主流程

            if (isMainFlow) {
                nextNode = flowConstant.getNextNodeName(currentNode);
            } else {
                nextNode = HfrwFlowConstant.getSubNextNodeName(currentNode);
            }

            Map nextDbr = this.getNodeDbr(hfrwid, nextNode, "");
            dbrListByMap = busService.getDbrListByMap(nextDbr);
        }

        map.put("hfrw", hfrw); // 申请事项基本信息
        map.put("sqsx", sqsx); // 申请事项基本信息
        map.put("job", job); // 当前流转记录
        map.put("jobHistoryList", jobList); // 流程任务流传记录
        map.put("nextNodeDbrList", dbrListByMap); // 下环节待办人list
        map.put("nextNode", nextNode);

        return map;
    }

    /**
     * 更新基本信息
     * @param map 更新的字段
     * @param job 流程任务
     * @param hfrwid 回访任务id
     */
    public Result updateJbxx(HashMap<String,Object> map,String hfrwid,SpcySqsxJob job){
        SpcySqsxHfrwlc basicUpdate = spcySqsxHfrwlcService.getById(hfrwid);
        if (basicUpdate == null){
            return Result.error("当前回访任务【"+hfrwid+"】不存在，请重试");
        }
        SpcySqsxHfrwlc oldBean = basicUpdate;

        // 修改
        ConvertUtils.register(new DateConvert(), java.util.Date.class);
        try {
            BeanUtils.populate(basicUpdate,map);
            spcySqsxHfrwlcService.updateById(basicUpdate);

            // 科室签收人id
            if (StringUtils.isNotBlank(basicUpdate.getFksqsrid())){
                String dbr = this.getUserNameByUserId(basicUpdate.getFksqsrid());
                this.updateCzcsBlrJbxx(basicUpdate.getFksqsrid(), dbr, hfrwid, false, true);
            }
        } catch (IllegalAccessException e) {
            log.error("出错-保存回访任务【非法访问异常】,{}",e.getMessage());
        } catch (InvocationTargetException e) {
            log.error("出错-保存回访任务【调用TargetException】,{}",e.getMessage());
        }

        String logContent = "回访任务流程-基本信息修改: ";
        Map<String, Object> basicMap = ObjectToMapUtils.objectToMap(oldBean);
        logContent += LogUtils.BeanModifyMsg(basicUpdate,basicMap);

        if (job == null) {
            spcyLogService.addLogs(LogConstant.LOGS_SQSX_HFRWLC, logContent, hfrwid, SpcyConstant.LOGS_SYS_TYPE_XG, SpcyConstant.LOGS_SYS_TYPE_XG);
        }else {
            spcyLogService.addLogs(LogConstant.LOGS_SQSX_HFRWLC+"-"+job.getFhjmc(), logContent, hfrwid, LogConstant.LOGS_SQSX_BASIC, SpcyConstant.LOGS_SYS_TYPE_XG);
        }

        return Result.ok("保存成功");
    }

    /**
     * 更新处置措施办理人
     * @param isCzcs (true/处置措施)
     * @param isKsqs (true/科室签收)
     */
    public void updateCzcsBlrJbxx(String dbrid,String dbr,String hfrwid, boolean isCzcs, boolean isKsqs){
        SpcySqsxHfrwlc basicUpdate = spcySqsxHfrwlcService.getById(hfrwid);
        if (basicUpdate == null){
            log.error("当前回访任务【{}】不存在，请重试", hfrwid);
        }

        if (isCzcs) {
            basicUpdate.setFczcsrid(dbrid);
            basicUpdate.setFczcsr(dbr);
        }

        if (isKsqs){
            basicUpdate.setFksqsrid(dbrid);
            basicUpdate.setFksqsr(dbr);
        }

        String logContent = "回访任务流程-基本信息修改: ";
        if (isCzcs) {
            logContent += "处置措施人id[" + dbrid + "]; 处置措施人[" + dbr + "]";
        }

        if (isKsqs){
            logContent += "科室签收人id[" + dbrid + "]; 科室签收人[" + dbr + "]";
        }

        spcySqsxHfrwlcService.updateById(basicUpdate);

        spcyLogService.addLogs(LogConstant.LOGS_SQSX_HFRWLC, logContent, hfrwid, SpcyConstant.LOGS_SYS_TYPE_XG, SpcyConstant.LOGS_SYS_TYPE_XG);
    }

    /**
     * 通过用户ids获取对应的人员姓名
     */
    public String getUserNameByUserId(String userid){
        String username = "";
        List<String> usernameList = StringPatternUtils.getListByIds(userid);
        List<YcSysUser> userList = ycSysUserService.listByIds(usernameList);
        if (CollectionUtils.isNotEmpty(userList)){
            for (YcSysUser user : userList){
                if (StringUtils.isNotBlank(username)){
                    username += ","+user.getRealname();
                }else {
                    username += user.getRealname();
                }
            }
        }

        return username;
    }

    /**
     * 获取流转记录
     */
    public List<SpcySqsxJob> getJobListByHfrwid(String hfrwid){
        LambdaQueryWrapper<SpcySqsxJob> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SpcySqsxJob::getFpid, hfrwid);
        queryWrapper.eq(SpcySqsxJob::getFlcmc, flowConstant.getFlowName());
        queryWrapper.orderByAsc(SpcySqsxJob::getFfssj);
        queryWrapper.orderByAsc(SpcySqsxJob::getCreateTime);
        List<SpcySqsxJob> jobList = spcySqsxJobService.list(queryWrapper);

        return jobList;
    }

    /**
     * 通过回访任务id-获取当前处在环节
     * @param hfrwid
     * @return
     */
    public SpcySqsxJob getNowJobByHfrwid(String hfrwid){
        List<SpcySqsxJob> currentJobList = spcySqsxJobService.list(new LambdaQueryWrapper<SpcySqsxJob>()
                .eq(SpcySqsxJob::getFpid, hfrwid)
                .ne(SpcySqsxJob::getFblzt, SpcyConstant.BLZT_YB)
                .eq(SpcySqsxJob::getFlcmc, flowConstant.getFlowName())
                .orderByAsc(SpcySqsxJob::getFfssj));

        return currentJobList.get(0);
    }

    /**
     * 判断当前环节是否为子流程
     * @param currentNode 当前环节名称
     * @return
     */
    public boolean verifyMainFlow(String currentNode){
        if (StringUtils.isBlank(currentNode)){
            return false;
        }

        String nextNodeName = this.getNextNodeName(currentNode, null);
        if (StringUtils.isNotBlank(nextNodeName)){
            return true;
        }

        return false;
    }

    /**
     * 判断当前环节是否为子流程
     * @param currentNode 当前环节名称
     * @return
     */
    public boolean verifySubFlow(String currentNode){
        if (StringUtils.isBlank(currentNode)){
            return false;
        }

        String subNextNodeName = this.getSubNextNodeName(currentNode, null);
        if (StringUtils.isNotBlank(subNextNodeName)){
            return true;
        }

        return false;
    }

    /**
     * 判断是否存在子流程
     */
    public boolean verifyExistSubFlow(String sqid){

        List<SpcySqsxJob> jobList = spcySqsxJobService.list(new LambdaQueryWrapper<SpcySqsxJob>()
                .eq(SpcySqsxJob::getFhjmc, HfrwFlowConstant.SUB_HJMC_KSQS)
                .eq(SpcySqsxJob::getFpid, sqid)
                .eq(SpcySqsxJob::getFlcmc, flowConstant.getFlowName()));
        if (CollectionUtils.isEmpty(jobList)){
            return false;
        }

        return true;
    }

    /**
     * 验证子流程是否结束
     * @param sqid
     * @return
     */
    public boolean verifySubFlowIsEnd(String sqid){

        List<SpcySqsxJob> jobList = spcySqsxJobService.list(new LambdaQueryWrapper<SpcySqsxJob>()
                .eq(SpcySqsxJob::getFhjmc, HfrwFlowConstant.SUB_HJMC_FGLDSH)
                .eq(SpcySqsxJob::getFpid, sqid)
                .eq(SpcySqsxJob::getFblzt, SpcyConstant.BLZT_YB)
                .eq(SpcySqsxJob::getFlcmc, flowConstant.getFlowName()));
        if (CollectionUtils.isEmpty(jobList)){
            return false;
        }

        return true;
    }

    /**
     * 初始化主流程任务
     * @param hfrwid 回访任务id
     * @param currentUser
     * @return
     */
    public Result initJob(String hfrwid, CurrentUserVo currentUser){

        String nodeName = flowConstant.getFirstNode();

        //需要校验是否已经初始化过
        List<SpcySqsxJob> list = spcySqsxJobService.list(new LambdaQueryWrapper<SpcySqsxJob>()
                .eq(SpcySqsxJob::getFpid, hfrwid)
                .eq(SpcySqsxJob::getFhjmc, nodeName)
                .eq(SpcySqsxJob::getFlcmc, flowConstant.getFlowName())
        );

        if(list.size()>0){
            return Result.error("发起失败，已经发起过该流程了");
        }

        return this.createNextJob(flowConstant,hfrwid,null,currentUser,nodeName,"");
    }

    /**
     * 初始子流程任务
     */
    public Result initSubJob(String sqid, CurrentUserVo currentUser){

        String nodeName = flowConstant.getSubFirstNode();

        //需要校验是否已经初始化过
        List<SpcySqsxJob> list = spcySqsxJobService.list(new LambdaQueryWrapper<SpcySqsxJob>()
                .eq(SpcySqsxJob::getFpid, sqid)
                .eq(SpcySqsxJob::getFhjmc, nodeName)
                .eq(SpcySqsxJob::getFlcmc, flowConstant.getFlowName())
        );

        if(list.size()>0){
            return Result.error("发起失败，已经发起过该流程了");
        }

        return this.createNextJob(sqid,null,currentUser,nodeName,"");
    }

    /**
     * 提交当前环节的待办记录
     *  @param sqid 申请id
     *  @param jobId 当前环节id
     *  @param opinion 办理意见
     */
    public Result passJob(String sqid, String jobId, String opinion,String nextNodeName,String nextNodeDbrIds){
        //处理业务表的逻辑
        Result httpResult = this.passJob(flowConstant, sqid, jobId, opinion, nextNodeName, nextNodeDbrIds);
        return httpResult;
    }

    /**
     * 办结环节-并创建下一环节
     * @param job
     * @param pid
     * @param nextNodeName
     * @param nextNodeDbrIds
     * @param currentUser
     * @param opinion
     * @param isVerifyUser 是否验证用户权限
     * @return
     */
    private Result passJob(SpcySqsxJob job,String pid,String nextNodeName,String nextNodeDbrIds,CurrentUserVo currentUser,String opinion,boolean isVerifyUser){

        Result result = this.doJob(job,currentUser,opinion,isVerifyUser);
        // 生成下一环节的待办
        if(result.isSuccess()){
            job = (SpcySqsxJob)result.getResult();
            if(job.getFblzt().equals(SpcyConstant.BLZT_YB)){
                // 创建下一环节任务
                Result result1 = createNextJob(pid,job,currentUser,nextNodeName,nextNodeDbrIds);
                if (!result1.isSuccess()){
                    return Result.error(result1.getMessage());
                }else {
                    SpcySqsxJob newJob = (SpcySqsxJob) result1.getResult();
                    // 接收返回的流程任务，如果返回的流程任务id不相等，发送短信
                    busService.sendSmsToPassJob(newJob);
                }
            }
        }else{
            return Result.error(result.getMessage());
        }

        return Result.ok("操作成功");
    }

    /**
     * 办结当前流程任务
     * @param job
     * @param currentUser
     */
    private Result doJob(SpcySqsxJob job, CurrentUserVo currentUser, String opinion, boolean isVerifyUser){
        String blrId = "";
        String blr = "";
        if (currentUser != null) {
            blrId = currentUser.getId();
            blr = currentUser.getName();
        }
        if (job == null){
            return Result.error("当前流程任务不存在，请重试");
        }
        if(SpcyConstant.BLZT_YB.equals(job.getFblzt())){
            return Result.error("当前任务已提交");
        }
        if(StringUtils.isBlank(job.getFdbrid())){
            return Result.error("当前任务未指定办理人");
        }
        if (isVerifyUser) {
            if (!job.getFdbrid().contains(blrId)) {
                return Result.error("当前登录用户无此任务的办理权限");
            }
        }
        // 办理方式 竞争办理 、多人线性办理 、多人并行办理
        String blfs = job.getFblfs();
        if(StringUtils.isBlank(blfs)||blfs.equals(SpcyConstant.BLFS_DRJJ)){
            job.setFblr(blr);
            job.setFblsj(new Date());
            job.setFblyj(opinion);
            job.setFblzt(SpcyConstant.BLZT_YB);
            spcySqsxJobService.updateById(job);
            return Result.ok(job);
        }else if(blfs.equals(SpcyConstant.BLFS_DRXX)  || blfs.equals(SpcyConstant.BLFS_DRBX)){
            //先根据多个人线性和多人并行的逻辑获得下一办理人
            String nextBlrId ="";
            String nextBlr ="";
            if(blfs.equals(SpcyConstant.BLFS_DRXX)){
                String ydbrIds[] = job.getFydbrid().split(",");
                String ydbrs[] = job.getFydbr().split(",");
                for (int i=0;i<ydbrIds.length;i++){
                    String dbrId = ydbrIds[i];
                    //不考虑办理人id重复出现（一个人办多次）的情况
                    if(dbrId.equals(blrId)){
                        if(i+1<ydbrIds.length){
                            nextBlrId=ydbrIds[i+1];
                            nextBlr=ydbrs[i+1];
                            break;
                        }
                    }
                }
            }else{
                String dbrIds[] = job.getFdbrid().split(",");
                String dbrs[] = job.getFdbr().split(",");
                for (int i=0;i<dbrIds.length;i++){
                    String dbrId = dbrIds[i];
                    String dbr = dbrs[i];
                    //不考虑办理人id重复出现（一个人办多次）的情况
                    if(!dbrId.equals(blrId)){
                        nextBlrId=nextBlrId+(StringUtils.isBlank(nextBlrId)?"":",")+dbrId;
                        nextBlr=nextBlr+(StringUtils.isBlank(nextBlr)?"":",")+dbr;
                    }
                }
            }

            //如果存在下一办理人 就继续待办，多人办理意见用@@分隔，办理时间、办理人、意见 用|分隔
            job.setFblr(blr);
            job.setFblsj(new Date());
            String blyj=(job.getFblyj()==null?"":job.getFblyj())+(StringUtils.isBlank(job.getFblyj())?"":"@@")+ DateConversionUtils.DateToString(new Date()) +"|"+blr+"|"+ opinion;
            job.setFblyj(blyj);
            if(StringUtils.isBlank(nextBlrId)){
                job.setFblzt(SpcyConstant.BLZT_YB);
            }else{
                job.setFblzt(SpcyConstant.BLZT_DB);
                job.setFdbrid(nextBlrId);
                job.setFdbr(nextBlr);
            }
            spcySqsxJobService.updateById(job);
            return Result.ok(job);
        }
        return Result.error("待办任务未指定办理方式");
    }

    /**
     * 创建下环节流程任务
     * @param sqid
     * @param currentJob
     * @param currentUser
     * @param nextNodeName
     * @param nextNodeDbrIds
     * @return
     */
    public Result createNextJob(String sqid,SpcySqsxJob currentJob, CurrentUserVo currentUser,String nextNodeName,String nextNodeDbrIds){

        if (currentJob != null) {
            nextNodeName = getNextNodeName(currentJob.getFhjmc(), nextNodeName);
        }else {
            if (StringUtils.isBlank(nextNodeName)){
                return Result.error("下环节不能为空");
            }
        }

        if(nextNodeName.equals(HfrwFlowConstant.HJMC_LCJS)){
            SpcySqsxJob job = new SpcySqsxJob();
            log.info("流程结束");
            return Result.ok(job);
        }

        Map map = this.getNodeDbr(sqid,nextNodeName,nextNodeDbrIds);
        nextNodeDbrIds = map.get("dbrId").toString();
        String nextNodeDbrs = map.get("dbr").toString();

        if(StringUtils.isBlank(nextNodeDbrIds)){
            return Result.error("获取不到下一环节待办人");
        }

        SpcySqsxJob job = new SpcySqsxJob();
        job.setId(GetUuIdUtils.NotReplaceUuId());
        if(currentJob != null){
            job.setFsyhjid(currentJob.getId());
        }
        job.setFpid(sqid);
        job.setFhjmc(nextNodeName);

        if (currentUser != null) {
            job.setFfsrid(currentUser.getId());
            job.setFfsrmc(currentUser.getName());
        }

        job.setFfssj(new Date());

        job.setFdbrid(nextNodeDbrIds);
        job.setFdbr(nextNodeDbrs);
        job.setFydbrid(nextNodeDbrIds);
        job.setFydbr(nextNodeDbrs);

        job.setFblfs(flowConstant.getBlfs(nextNodeName));
        job.setFblzt(SpcyConstant.BLZT_DB);
        job.setFlcmc(flowConstant.getFlowName());
        spcySqsxJobService.save(job);

        return Result.ok(job);
    }

    /**
     * 主流程-下环节名称
     * @param currentNodeName 可为空(如果为空，nextNodeName不为空)
     * @param nextNodeName 可为空(如果为空，currentNodename不为空)
     * @return
     */
    private String getNextNodeName(String currentNodeName,String nextNodeName){
        if (StringUtils.isNotBlank(nextNodeName)){
            return nextNodeName;
        }else{
            return flowConstant.getNextNodeName(currentNodeName);
        }
    }

    // 子流程-下环节名称
    public static String getSubNextNodeName(String currentNodeName,String nextNodeName){
        if (StringUtils.isNotBlank(nextNodeName)){
            return nextNodeName;
        }else{
            return HfrwFlowConstant.getSubNextNodeName(currentNodeName);
        }
    }

    // 获取当前环节待办人
    public Map getNodeDbr(String hfrwid,String nodeName, String dbrIds){
        Map map = new HashMap();
        String dbrId = "";
        String dbr = "";

        if(StringUtils.isNotBlank(dbrIds)){

            dbr = getDbrsByIds(dbrIds);
            dbrId = dbrIds;

        }else{

            // 回访计划 (质量管理与科研科办理，从已移送库选择对象，可选本次回访的和候补的、回访时间、回访地点）
            if (nodeName.equals(HfrwFlowConstant.HJMC_HFJH)){
                Map kzMap = getzltxwjfzrByDeptName(SpcyConstant.DEPT_NAME_ZHYWK);
                dbrId = kzMap.get("dbrId").toString();
                dbr = kzMap.get("dbr").toString();
            }

            // 回访计划审核（质量管理与科研科科长办理）
            if (nodeName.equals(HfrwFlowConstant.HJMC_HFJHSH)){
                Map kzMap = getKsfzrByDeptName(SpcyConstant.DEPT_NAME_ZHYWK);
                dbrId = kzMap.get("dbrId").toString();
                dbr = kzMap.get("dbr").toString();
            }

            // 回访计划审批（质量管理与科研科科长办理）
            if (nodeName.equals(HfrwFlowConstant.HJMC_HFJHSP)){
                Map kzMap = getKsfzrByDeptName(SpcyConstant.DEPT_NAME_ZHYWK);
                dbrId = kzMap.get("dbrId").toString();
                dbr = kzMap.get("dbr").toString();
            }

            // 回访计划实施（质量管理与科研科办理，支持以下操作：发给每个企业一个函；将企业按辖区归入对应的分局，
            //     *      一个区域一个函；支持分发二维码或者短信，受访企业可以线上填写回访记录；
            //     *      需要能按各个企业上传对应的回访记录；可以选反馈意见处置科室，填写对应的反馈意见，处置截止时间，选接科室受人）
            if (nodeName.equals(HfrwFlowConstant.HJMC_HFJHSS)){

                // 处置科室
//                SpcySqsxHfrwlc hfrw = spcySqsxHfrwlcService.getById(hfrwid);

                // 科室经办人
                /*Map kzMap = getKsjbrByDeptName(hfrw.getFfkyjczks());
                dbrId = kzMap.get("dbrId").toString();
                dbr = kzMap.get("dbr").toString();*/

                Map kzMap = getzltxwjfzrByDeptName(SpcyConstant.DEPT_NAME_ZHYWK);
                dbrId = kzMap.get("dbrId").toString();
                dbr = kzMap.get("dbr").toString();
            }

            // 回访结果审核（质量管理与科研科科长办理）
            if (nodeName.equals(HfrwFlowConstant.HJMC_HFJGSH)){
                Map kzMap = getKsfzrByDeptName(SpcyConstant.DEPT_NAME_ZHYWK);
                dbrId = kzMap.get("dbrId").toString();
                dbr = kzMap.get("dbr").toString();
            }

            // 回访结果审批（质量管理与科研科分管力领导办理）
            if (nodeName.equals(HfrwFlowConstant.HJMC_HFJGSP)){
                // 分管领导
                Map kzMap = getKsFgldByDeptName(SpcyConstant.DEPT_NAME_ZHYWK);
                dbrId = kzMap.get("dbrId").toString();
                dbr = kzMap.get("dbr").toString();
            }

            // 反馈意见处置（质量管理与科研科办理，支持各科室完成以后自动提交）
            if (nodeName.equals(HfrwFlowConstant.HJMC_FKYJCZ)){
                Map kzMap = getzltxwjfzrByDeptName(SpcyConstant.DEPT_NAME_ZHYWK);
                dbrId = kzMap.get("dbrId").toString();
                dbr = kzMap.get("dbr").toString();
            }

            // 归档办结（质量管理与科研科办理，生产台账）
            if (nodeName.equals(HfrwFlowConstant.HJMC_GDBJ)){
                Map kzMap = getzltxwjfzrByDeptName(SpcyConstant.DEPT_NAME_ZHYWK);
                dbrId = kzMap.get("dbrId").toString();
                dbr = kzMap.get("dbr").toString();
            }

            // 科室签收（选定的接收人办理）
            if (nodeName.equals(HfrwFlowConstant.SUB_HJMC_KSQS)){

                // 处置科室
                SpcySqsxHfrwlc hfrw = spcySqsxHfrwlcService.getById(hfrwid);

                if (StringUtils.isBlank(hfrw.getFksqsrid()) && StringUtils.isNotBlank(hfrw.getFfkyjczks())) {
                    // 科室经办人
                    Map kzMap = getKsjbrByDeptName(hfrw.getFfkyjczks());
                    dbrId = kzMap.get("dbrId").toString();
                    dbr = kzMap.get("dbr").toString();

                }else {

                    dbrId = hfrw.getFksqsrid();
                    dbr = hfrw.getFksqsr();
                }
            }

            // 填处置措施（选择的处置人办理，支持上传多个附件）
            if (nodeName.equals(HfrwFlowConstant.SUB_HJMC_TCZCS)){

                // 处置科室
                SpcySqsxHfrwlc hfrw = spcySqsxHfrwlcService.getById(hfrwid);

                if (StringUtils.isBlank(hfrw.getFczcsrid()) && StringUtils.isNotBlank(hfrw.getFfkyjczks())) {
                    // 科室经办人
                    Map kzMap = getKsjbrByDeptName(hfrw.getFfkyjczks());
                    dbrId = kzMap.get("dbrId").toString();
                    dbr = kzMap.get("dbr").toString();

                }else {

                    dbrId = hfrw.getFczcsrid();
                    dbr = hfrw.getFczcsr();
                }
            }

            // 科室审核（对应科室科长办理）
            if (nodeName.equals(HfrwFlowConstant.SUB_HJMC_KSSH)){

                // 处置科室
                SpcySqsxHfrwlc hfrw = spcySqsxHfrwlcService.getById(hfrwid);

                // 科室经办人
                Map kzMap = getKsfzrByDeptName(hfrw.getFfkyjczks());
                dbrId = kzMap.get("dbrId").toString();
                dbr = kzMap.get("dbr").toString();
            }

            // 分管领导审核（对应科室分管领导）
            if (nodeName.equals(HfrwFlowConstant.SUB_HJMC_FGLDSH)){

                // 处置科室
                SpcySqsxHfrwlc hfrw = spcySqsxHfrwlcService.getById(hfrwid);
                String ffkyjczks = hfrw.getFfkyjczks();

                // 分管领导
                Map kzMap = getKsFgldByDeptName(ffkyjczks);
                dbrId = kzMap.get("dbrId").toString();
                dbr = kzMap.get("dbr").toString();
            }

        }

        map.put("dbrId",dbrId);
        map.put("dbr",dbr);
        return map;
    }

    // 获取当前环节待办人
    public Map getNodeDbr(String nodeName, String dbrIds){
        return this.getNodeDbr(null,nodeName,dbrIds);
    }

    // 根据待办人id，获取名称拼接起来
    private String getDbrsByIds(String dbrIds){
        //把待办人按id查出来  把名字拼起来
        String dbr = "";
        List<String> dbrIdsList = Arrays.asList(dbrIds.split(","));
        List<YcSysUser> sysUserList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(dbrIdsList)){
            sysUserList = ycSysUserService.listByIds(dbrIdsList);
        }

        if (CollectionUtils.isNotEmpty(sysUserList)){
            for (YcSysUser user : sysUserList){
                dbr += user.getRealname() + ",";
            }
        }

        return dbr;
    }

    // 对应科室的 科室负责人
    public Map getKsfzrByDeptName(String deptName){
        Map map = new HashMap();
        String dbrId = "";
        String dbr = "";
        List<GetKsKz> ksKzObject = new ArrayList<>();
        ksKzObject = ycSysUserService.getKsKzObject(deptName, SpcyConstant.GW_NAME_KZ);
        if (CollectionUtils.isNotEmpty(ksKzObject)) {
            for (GetKsKz ksKz : ksKzObject) {
                dbrId += ksKz.getId()+",";
                dbr += ksKz.getRealname()+",";
            }
        }

        map.put("dbrId",dbrId);
        map.put("dbr",dbr);
        return map;
    }

    // 对应科室的 经办人
    public Map getKsjbrByDeptName(String deptName){
        Map map = new HashMap();
        String dbrId = "";
        String dbr = "";
        List<GetKsKz> ksKzObject = new ArrayList<>();
        ksKzObject = ycSysUserService.getKsKzObject(deptName, SpcyConstant.GW_NAME_JBR);

        if (CollectionUtils.isNotEmpty(ksKzObject)) {
            for (GetKsKz ksKz : ksKzObject) {
                dbrId += ksKz.getId()+",";
                dbr += ksKz.getRealname()+",";
            }
        }

        map.put("dbrId",dbrId);
        map.put("dbr",dbr);
        return map;
    }

    // 获取对应科室的 分管领导
    public Map getKsFgldByDeptName(String deptName){
        Map map = new HashMap();
        String dbrId = "";
        String dbr = "";

        YcSysUser fgldUserBydept = sysUserFgldService.getFgldUserBydept(deptName);
        if (fgldUserBydept != null) {
            dbrId = fgldUserBydept.getId();
            dbr = fgldUserBydept.getRealname();
        }

        map.put("dbrId",dbrId);
        map.put("dbr",dbr);
        return map;
    }

    // 获取主办人
    public Map getZbrBySqsxId(String sqsxId){
        Map map = new HashMap();
        String dbrId = "";
        String dbr = "";

        SqsxZbrVo zbrVo = spcySqsxBaiscService.selectFzbrById(sqsxId);
        if (zbrVo != null && StringUtils.isNotBlank(zbrVo.getFzbr())){

            dbrId = zbrVo.getFzbr();

            if (StringUtils.isNotBlank(zbrVo.getFjbrmc())){
                dbr = zbrVo.getFjbrmc();
            }else {
                List<String> userIdList =  StringPatternUtils.getListByIds(zbrVo.getFzbr());
                List<YcSysUser> userList = ycSysUserService.findRealnameListByIds(userIdList);
                for (int i = 0; i<userList.size(); i++){
                    if (StringUtils.isBlank(dbr)) {
                        dbr = userList.get(i).getRealname();
                    } else {
                        dbr += "," + userList.get(i).getRealname();
                    }
                }
            }


        }

        map.put("dbrId",dbrId);
        map.put("dbr",dbr);
        return map;
    }

    // 对应科室的 回访任务负责人
    public Map getzltxwjfzrByDeptName(String deptName){
        Map map = new HashMap();
        String dbrId = "";
        String dbr = "";
        List<GetKsKz> ksKzObject = new ArrayList<>();
        ksKzObject = ycSysUserService.getKsKzObject(deptName, SpcyConstant.GW_HFRW_FZR);

        if (CollectionUtils.isNotEmpty(ksKzObject)) {
            for (GetKsKz ksKz : ksKzObject) {
                dbrId += ksKz.getId()+",";
                dbr += ksKz.getRealname()+",";
            }
        }

        map.put("dbrId",dbrId);
        map.put("dbr",dbr);
        return map;
    }

    // 获取部门
    public String getDeptName(String ywflcode){

        String deptName = SpcyConstant.getYwclNameByCode(ywflcode);

        // 获取部门
        List<YcSysOrg> deptList = ycSysOrgService.list(new LambdaQueryWrapper<YcSysOrg>()
                .like(YcSysOrg::getOrgName, deptName));
        if (CollectionUtils.isNotEmpty(deptList)){
            return deptList.get(0).getOrgName();
        }

        return "";
    }

}
